package me.zhengjie.modules.inspection.service.impl;

import me.zhengjie.modules.equipment.domain.TEquipment;
import me.zhengjie.modules.equipment.repository.TEquipmentRepository;
import me.zhengjie.modules.inspection.domain.TInspectionTask;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.inspection.repository.TInspectionTaskRepository;
import me.zhengjie.modules.inspection.service.TInspectionTaskService;
import me.zhengjie.modules.inspection.service.dto.TInspectionTaskDTO;
import me.zhengjie.modules.inspection.service.dto.TInspectionTaskQueryCriteria;
import me.zhengjie.modules.inspection.service.mapper.TInspectionTaskMapper;
import me.zhengjie.modules.workorder.service.dto.TAccidentQueryCriteria;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.*;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author xuyukun
* @date 2019-07-21
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TInspectionTaskServiceImpl implements TInspectionTaskService {

    @Autowired
    private TInspectionTaskRepository tInspectionTaskRepository;

    @Autowired
    private TInspectionTaskMapper tInspectionTaskMapper;

    @Autowired
    private TEquipmentRepository tEquipmentRepository;

    @Override
    public Object queryAll(TInspectionTaskQueryCriteria criteria, Pageable pageable){
        Page<Map<String,Object>> tasksPage = tInspectionTaskRepository.queryInspectionTask(pageable);
        //Page<TInspectionTask> page = tInspectionTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        //return PageUtil.toPage(page.map(tInspectionTaskMapper::toDto));
        List<TEquipment> equipmentList = tEquipmentRepository.findAll() ;
        HashMap<Integer,TEquipment> equipmentHashMap = new HashMap<Integer,TEquipment>();
        equipmentList.forEach((TEquipment e)->{ equipmentHashMap.put(e.getId(),e); });

        return PageUtil.toPage(tasksPage.map((Map<String,Object> map)-> {
            TInspectionTaskDTO taskDTO = new TInspectionTaskDTO() ;
            taskDTO.setId( ((BigInteger)map.get("task_id")).longValue() ) ;
            taskDTO.setPlanid( ((BigInteger)map.get("id")).longValue() ) ;
            taskDTO.setPlanName((String)map.get("plan_name"));
            taskDTO.setToolName((String)map.get("tool_name")); //名字
            taskDTO.setToolId((String)map.get("tool_name")); //id 数组

            taskDTO.setObjId( ((BigInteger)map.get("obj_id")).longValue() );
            String objName = (String)map.get("obj_name");

            taskDTO.setObjName( objName );
            String[] equipIdArray = objName.split(",");
            String[] equipNames = new String[equipIdArray.length];  //设备名,即巡检对象名称
            for(int i = 0; i < equipIdArray.length; i++) {
                String id = equipIdArray[i];
                TEquipment e = equipmentHashMap.get(Integer.valueOf(id)) ;
                if(e != null) {
                    equipNames[i] = e.getEqptcode() + "/" + e.getEqptname();
                }
            }
            //taskDTO.setVehTypeName( (String)map.get("veh_type_name") );
            taskDTO.setVehTypeName(StringUtils.join(equipNames,","));  //设备名,点分

            taskDTO.setTemplateId( ((BigInteger)map.get("template_id")).longValue() );
            taskDTO.setTemplateName( (String)map.get("template_name") );
            taskDTO.setPlanDesc( (String)map.get("plan_desc") );
            taskDTO.setPeriodId( ((BigInteger)map.get("period_id")).longValue() );
            taskDTO.setPeriodName( (String)map.get("period_name") );
            taskDTO.setInspectorId( ((BigInteger)map.get("inspector_id")).longValue() );
            taskDTO.setInspectorName( (String)map.get("inspector_name") );

            taskDTO.setStartTime( (Timestamp)map.get("start_time") );
            taskDTO.setEndTime( (Timestamp)map.get("end_time") );
            taskDTO.setOperateTime( (Timestamp)map.get("operate_time") );
            taskDTO.setState( (Integer)map.get("state2") );
            return taskDTO ;
        }));
    }

    @Override
    public Object queryAll(TInspectionTaskQueryCriteria criteria){
        return tInspectionTaskMapper.toDto(tInspectionTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TInspectionTaskDTO findById(Long id) {
        Optional<TInspectionTask> tInspectionTask = tInspectionTaskRepository.findById(id);
        ValidationUtil.isNull(tInspectionTask,"TInspectionTask","id",id);
        return tInspectionTaskMapper.toDto(tInspectionTask.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TInspectionTaskDTO create(TInspectionTask resources) {
        return tInspectionTaskMapper.toDto(tInspectionTaskRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TInspectionTask resources) {
        Optional<TInspectionTask> optionalTInspectionTask = tInspectionTaskRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTInspectionTask,"TInspectionTask","id",resources.getId());

        TInspectionTask tInspectionTask = optionalTInspectionTask.get();
        // 此处需自己修改
        resources.setId(tInspectionTask.getId());
        tInspectionTaskRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        tInspectionTaskRepository.deleteById(id);
    }
    
    @Override
	public Object queryAllWithOrder(TInspectionTaskQueryCriteria criteria) {
		return tInspectionTaskMapper.toDto(tInspectionTaskRepository.findInspectionTaskWithOrder());
	}
}